package com.thbent.alarm.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thbent.alarm.dao.UserDao;
import com.thbent.alarm.exception.LoginException;
import com.thbent.alarm.model.User;
import com.thbent.alarm.service.UserService;
import com.thbent.alarm.utils.TypeConvert;

@Service("userService")
public class UserServiceImpl implements UserService {

	private static final Logger LOGGER = LogManager.getLogger("userService");

	@Autowired
	private UserDao userDao;

	@Override
	public User findByUserName(String username) {
		return userDao.findByUserName(username);
	}

	@Override
	@Transactional(rollbackFor = { Throwable.class })
	public void modifyErrorCount(String username, Integer errorCount) {
		Map<String, Object> paramMap = new HashMap<>();
		paramMap.put("username", username);
		paramMap.put("errorCount", errorCount);
		userDao.modifyErrorCount(paramMap);
	}

	@Override
	@Transactional(rollbackFor = { Throwable.class })
	public void modifyPassword(Map<String, Object> paramMap) {
		userDao.modifyPassword(paramMap);
	}

	@Override
	public User login(String username, String password) throws LoginException {
		User user = findByUserName(username);
		if (user == null) {
			throw new LoginException("用户名不存在！");
		} else {// 查询到的用户名存在
			int errorCount = TypeConvert.integerToInt(user.getErrorCount());
			if (password.equals(user.getPassword())) {
				if (errorCount != 0) {
					modifyErrorCount(username, 0);
				}
				return user;
			} else {
				modifyErrorCount(username, ++errorCount);
				throw new LoginException("密码错误！", errorCount);
			}
		}

	}

	/**
	 * 修改密码
	 */

	@Override
	public User changePassword(String username, String newPassword) {
		userDao.changePassword(username, newPassword);
		User user = findByUserName(username);
		return user;
	}

}
